package com.kfm.servlet;

import com.kfm.model.Account;
import com.kfm.service.FileService;
import com.kfm.util.Contains;
import com.kfm.util.LoginUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (LoginUtil.isNonLogin(req.getSession())){
            resp.sendRedirect("login");
            return;
        }
        req.getRequestDispatcher("WEB-INF/upload.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取上传的文件对象
        Part part = request.getPart("file");

        if (part != null) {
            FileService fileService = new FileService();

            // 获取到当前登录用户的信息
            Object attribute = getServletContext().getAttribute(Contains.LOGIN_FLAG);

            if (attribute instanceof Account account){
                int result = fileService.save(part, account.getId());

                if (result > 0){
                    response.sendRedirect("index");
                    return;
                }
            }
        }
        response.sendRedirect("upload");
    }
}
